﻿module Sustainalytics.Container {
    import Company = Sustainalytics.Company;
    import Research = Sustainalytics.Research;    
    import LRTM = Sustainalytics.LRTM;
    import Authentication = Sustainalytics.Authentication;

    export class ContainerController extends Research.ResearchPageController {
        //when reusing this controller, moduleName should be an input parameter. same as acceptedUrl        
        private acceptedUrl: string;

        private static researchController: Research.CompanyResearchController = null;       
        private static authenticationService: Authentication.AuthenticationService = null;

        public iFrameUrl: string;
        public static listening: boolean = false;

        constructor(            
            protected $rootScope: any,
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $location: ng.ILocationService,
            protected $sce: ng.ISCEService,
            protected $window: any,
            protected $timeout: ng.ITimeoutService,
            protected $modal: Common.IModal,
            protected $http: ng.IHttpService,
            protected RoutingService: Routing.IRoutingService,
            protected CompanyService: Company.ICompanyService,
            protected CompanyResearchService: Research.ICompanyResearchService,
            protected MostRecentActivityService: MostRecentActivity.IMostRecentActivityService,
            protected MostActiveReportService: MostActiveReports.MostActiveReportService,
            protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            protected AuthenticationService: Authentication.IAuthenticationService,
            protected staticObjects: Common.IStaticObjects) {
            
            super($scope, $q, $location, RoutingService, CompanyService);            
            
            this.acceptedUrl = this.$location.protocol() + "://" + this.$location.host() + "/angularcli";
            //show preloader on page load
            this.$rootScope.loading = true;

            //get authentication service. Just one instance required
            if (ContainerController.authenticationService == null)
                ContainerController.authenticationService = new Authentication.AuthenticationService($q, $http, staticObjects, $location, $rootScope, $timeout, $window);
            
            var moduleName = this.$routeParams.module;
            if (this.$routeParams.companyName) {
                //if container has company specific page, load the company research controller. Just one instance required
                if (ContainerController.researchController == null)
                    ContainerController.researchController = new Research.CompanyResearchController($rootScope, $scope, $q, $location, RoutingService, CompanyService, CompanyResearchService, MostRecentActivityService, $modal);                            

                //get company id by urlFriendlyName (could not find a better way to get it)
                var companyPromise = this.CompanyService.getByNameUrlFriendly(this.$routeParams.companyName);

                //TODO: check user has permission to view the research on this company. If not, reject promise

                companyPromise.success((company) => {
                    var coverageEntityname = company.isCoverageEntity ? company.companyName : "NotApplicable";
                    this.iFrameUrl = this.$sce.trustAsResourceUrl(this.acceptedUrl + '/#/' + moduleName + '/' + company.id + '/' + coverageEntityname);
                });
            }
            else
                this.iFrameUrl = this.$sce.trustAsResourceUrl(this.acceptedUrl + '/#/' + moduleName);

            if (ContainerController.listening == false) {
                ContainerController.listening = true;
                $window.addEventListener("message", (event: MessageEvent) => {
                    //only when event origin matches the accepted url, we resize the frame and return auth_token                
                    if (this.acceptedUrl.indexOf(event.origin) > -1) {
                        var message = JSON.parse(event.data);

                        //if operation is to connect
                        if (message.operation == 0) {
                            //on IE9, postMessage works only if message is sent as string
                            this.sendAuthData(event, this.$rootScope.authData.access_token);                          
                        }

                        //if operation is for resize
                        if (message.operation == 1) {
                            document.getElementById('iframeContainer').style.height = message.param + "px";
                        }

                        //if operation is to show preloader
                        if (message.operation == 2) {
                            this.$rootScope.loading = true;
                        }

                        //if operation is to hide preloader
                        if (message.operation == 3) {
                            this.$rootScope.loading = false;
                        }

                        //if operation is to add company to portfolio
                        if (message.operation == 4 &&
                            message.param.companyId) {
                            ContainerController.researchController.openSaveRiskPortfolio(message.param.companyId, message.param.companyName, message.param.tickerExchange);
                        }

                        //if operation is to download report (full or summary)
                        if (message.operation == 5 &&
                            message.param.companyId) {
                            this.downloadRiskReport(message.param.companyId, message.param.companyUrlFriendlyName, message.param.isSummaryReport);
                        }

                        //if refresh token is required
                        if (message.operation == 6) {
                            ContainerController.authenticationService.refreshToken().then((data) => {
                                this.sendAuthData(event, this.$rootScope.authData.access_token);
                            });
                        }
                    }
                    else
                        console.log('Unauthorized acces for postMessage(' + this.acceptedUrl + ',' + event.origin + ')');
                });                
            }
        }

        private sendAuthData(event, token) {            
            event.source.postMessage(JSON.stringify({
                token: token,
                userId: this.$rootScope.userInfo.userId,
                accountId: this.$rootScope.userInfo.accountId,
                loginTime: this.$rootScope.authData.loginTime,
                expiresIn: this.$rootScope.authData.expires_in
            }), event.origin);
        }

        private downloadRiskReport(companyId, companyUrlFriendlyName, isSummaryReport): void {
            var ctx = this;
            var now = new Date();

            var nameNoGuid = companyUrlFriendlyName.substring(0, companyUrlFriendlyName.length - 37);
            var reportName = nameNoGuid + "_RiskRatingsReport_" + ('0' + now.getDate()).slice(-2) + ('0' + (1 + now.getMonth())).slice(-2) + now.getFullYear();

            if (isSummaryReport) {
                reportName = nameNoGuid + "_RiskSummaryReport_" + ('0' + now.getDate()).slice(-2) + ('0' + (1 + now.getMonth())).slice(-2) + now.getFullYear();
            }

            ctx.MostActiveReportService.addReport(companyId);

            var dateNow = new Date();
            var dateNowString = [dateNow.getDate(), dateNow.getMonth() + 1, dateNow.getFullYear()].join("/");
            var gaObject: any = {
                Date: dateNowString,
                AccountId: this.$rootScope.userInfo.accountId,
                UserId: this.$rootScope.userInfo.userId,
                CompanyId: companyId
            };

            var parameters = new RiskRatingsReportParametersDto();
            parameters.companyId = companyId;
            parameters.isSummaryReport = isSummaryReport;

            ctx.LongRunningTaskManagerService.runTask(reportName,
                JSON.stringify(parameters),
                LRTM.LongRunningTaskTypeEnum.RiskRatingsReport, true, null);

            this.sendGoogleAnalyticsBeacon('Research', "PDFRiskRatingReport default settings", JSON.stringify(gaObject));
        }

        private sendGoogleAnalyticsBeacon(eventCategory: string, eventAction: string, eventLabel: string) {
            var ctx = this;

            ga('create', 'UA-4379897-6', {
                'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.set', 'dimension1', ctx.$rootScope.userInfo.userId);

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': eventCategory, 'eventAction': eventAction, 'eventLabel': eventLabel
            });
        }
    }

    angular.module(containerModuleName).controller('ContainerController', ['$rootScope', '$scope', '$q', '$location', '$sce', '$window', '$timeout', '$modal', '$http',
        'RoutingService', 'CompanyService', 'CompanyResearchService', 'MostRecentActivityService', 'MostActiveReportService', 'LongRunningTaskManagerService', 'AuthenticationService', 'staticObjects', ContainerController]);
}